<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:include page="../../common.jsp"></jsp:include>
<%@ page import="java.util.Date,java.text.SimpleDateFormat" %>
<%
SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
String s=df.format(new Date());
%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加盘点单</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap-editable.css">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/bootstrap-editable.js"></script>
<script src="${pageContext.request.contextPath }/bootstrap-table/dist/extensions/editable/bootstrap-table-editable.js"></script>

<script type="text/javascript">
$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    
    //3.初始化时间控件
 	$('#data1').datetimepicker({
        format: 'YYYY-MM-DD',
        locale: moment.locale('zh-cn')
    });
    
	 //4.生成盘点单号
   	var s = "<%=s %>";
    $("#sid").val("pd"+s); 
    
    //5.查询所有仓库，调用下拉框多选初始化方法
    getStock();
    
    
    //6.添加盘点单
    $("#btn_add").click(function(){
    	
    	//备件id
    	var parCid = [];
    	//账面库存
    	var scount = [];
    	//实际库存
    	var acount = [];
    	
    	var a= $('#tb_departments').bootstrapTable('getData');
    	if(a.length  <= 0) {
    		//没有，提示
			toastr.warning("该仓库中没有物品！"); 
			return;
    	}else {
    		 for ( var i = 0; i < a.length; i++) {
 	    		if(a[i].cremark5 == "" || a[i].cremark5 == null  || a[i].cremark5 == undefined) {
 	    			//没有，提示
	 	   			toastr.warning("数据不完整"); 
	 	   			return;
 	    		}else {
 	    			parCid.push(a[i].cremark6);
 	    			scount.push(a[i].cremark4);
 	    			acount.push(a[i].cremark5);
 	    		}
 			}
    	}
    	
    	//获取盘点单号
    	var sid=$("#sid").val();
    	//获取盘点时间
    	var data=$("#data").val();
    	//获取盘点人
    	var firchek=$("#firchek").val();
    	//获取仓库
    	var area=$("#area").val();
    	 if(data == "" || data == null  || data == undefined) {
    		 toastr.warning("请填写盘点时间");  
    		 return;
    	 }
    	 if(firchek == "" || firchek == null  || firchek == undefined) {
    		 toastr.warning("请填写盘点人");  
    		 return;
    	 }
    	 if(area == "" || area == null  || area == undefined) {
    		 toastr.warning("请填写仓库");  
    		 return;
    	 }
    	 
    	 
		$.ajax({ 
    		type: "post",  
	        url: "${pageContext.request.contextPath }/check/insertCheck.do",  
	        data: {sid:sid,data:data,firchek:firchek,area:area},  
	        success: function (data) {
	        	if(data == 1){
	        		//盘点单录入成功后，添加盘点详情
	        		$.ajax({
	        	        type: "get",
	        	        url: '${pageContext.request.contextPath }/checkDetail/insertCheckDetail.do?parCid='+parCid+'&scount='+scount+'&acount='+acount+'&sid='+sid,
	        	        // 数组和产品名称作为参数
	        	        //data:{"parCid":parCid,"scount":scount,"acount":acount,"sid":sid,"cid":area}, 
	        	       //data:"parCid ="+ parCid,
	        	        success: function (data) {
	        	        	if(data == 1){
		        	        	$('#btn_add').attr('disabled',true);
		   					 	toastr.success("保存成功");   
		   						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
		   							//跳转到列表页面
		   							window.location.href="${pageContext.request.contextPath }/check/pageToCheck.do";
		   						},2000);
	        	        	}else {
	       	        		 	toastr.warning("盘点详情保存失败");   
	        	        	}
	        	        }
	        	    });
	        	}else {
	        		 toastr.warning("盘点单保存失败");   
	        	}
			}
	    });
    });
});

//查询所有仓库
function getStock() {
	//清空下拉框节点
	$("#area").empty();
	$.ajax({
		type : "post",
		 url: "${pageContext.request.contextPath }/check/selectAllStock.do",        //请求地址
		success : function(data) {
			var str = "";
			var json = eval('(' + data + ')');
			for (var i = 0; i < json.length; i++) {
				str += '<option value="'+json[i].locationid+'">'
						+ json[i].locationname + '</option>';
			}
			$("#area").append('<option value="" selected="selected">请选择</option>');
			$("#area").append(str);
			$("#area").selectpicker('refresh');
		}
	});
} 

//根据仓库id查询统计该仓库所有的库存信息
function selectCom() {
	//获取仓库
	var area=$("#area").val();
	 $('#tb_departments').bootstrapTable(  
             "refresh",  
             {  
           	  url:'${pageContext.request.contextPath }/checkDetail/selectComByArea.do?area='+area
             }  
    	 ); 
}
	
var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_departments').bootstrapTable({
        	method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: false,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 600,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "componentId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            columns: [[{
                field: 'cremark6',
                title: '备件id',
                visible: false
            }, {
		    	field: 'cremark2',
		        title: '备件型号'
		    }, {
		        field: 'cremark4',
		        title: '账面库存'
		    }, {
		    	field: 'cremark5',
		        title: '实际库存',
		        editable: {
                    type: 'text',
                    title: '实际库存',
                    validate: function (v) {
                        if (!v) return '实际库存不能为空';
                        if (isNaN(v)) return '必须是数字';
                    }
                }  
		    }]]
		  });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};


</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom: 0px;">
		<button id="btn_add" type="button" class="btn btn-default" >
			<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>保存
		</button>
		<button id="btn_back" type="button" class="btn btn-default" onclick="javascript:history.back()" >
           	<span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>退出
       	</button>
	</div>
	<div class="panel-body" style="padding-bottom: 0px;">
		<div class="row">
			<div class="col-lg-2">
			  <label for="phone" class="control-label">盘点单号:</label>
			  <input type="text" class="form-control" id="sid" name="sid" readonly="readonly">
			</div>
			<div class="col-lg-2">
				<label class="control-label">盘点日期:</label>
                <div class='input-group date' id='data1' >
                   <input type='text' class="form-control" name="data" id="data"/>
                   <span class="input-group-addon">
                       <span class="glyphicon glyphicon-calendar"></span>
                   </span>
               </div>
			</div>
			<div class="col-lg-2">
			  <label for="phone" class="control-label">盘点人:</label>
			  	<input class="form-control" type="text" id="firchek">
			</div>
			
			<div class="col-lg-2">
			  <label for="phone" class="control-label">盘点仓库:</label>
			  	<select id="area" class="js-data-example-ajax form-control" onchange="selectCom()">
   		        </select>
			</div>
		</div>
		
		<table id="tb_departments"></table>
	</div>
</body>
</html>